package com.hisense.ovcloud.apicontrol.tool;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.LFUCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.locks.ReentrantReadWriteLock;

@Slf4j
@Component
public class LocalLFUCacheUtil {
    private final ReentrantReadWriteLock rrwLock = new ReentrantReadWriteLock();

    @Value("${localcache.capacity:5000}")
    private int capacity;

    private final LFUCache<String, String> timeCache;

    LocalLFUCacheUtil(){
        timeCache = CacheUtil.newLFUCache(capacity);
    }

    public void setToCache(String k, String v){
        try {
            rrwLock.writeLock().lock();
            timeCache.put(k, v);
        } catch (Exception e) {
            log.error("failed to set cache for key {}, error is {}", k, e.getMessage());
        } finally {
            rrwLock.writeLock().unlock();
        }
    }

    public String getFromCache(String k){
        try {
            rrwLock.readLock().lock();
            return timeCache.get(k);
        } catch (Exception e) {
            log.error("failed to get cache for key {}, error is {}", k, e.getMessage());
        } finally {
            rrwLock.readLock().unlock();
        }
        return null;
    }

    public boolean exists(String k){
        try {
            rrwLock.readLock().lock();
            return timeCache.containsKey(k);
        } catch (Exception e) {
            log.error("failed to detect if key {} exists in cache, error is {}", k, e.getMessage());
        } finally {
            rrwLock.readLock().unlock();
        }
        return false;
    }
}
